﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MarginTrading.Entity;
using MarginTrading.Services;

namespace MarginTrading.Forms
{
    public partial class InitialPortfolios : Form
    {

        String BROKER_CODE = "";
        String CDSIniPortHdrFile = "Headers\\PortfolioIni.hdr";
        String CDSClientHdrFile = "Headers\\Clients.hdr";
        public InitialPortfolios()
        {
            InitializeComponent();
            try
            {
                Config BrokerCodeConfig = ConfigServices.GetConfigByName("Company Code");
                BROKER_CODE = BrokerCodeConfig.Value;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Database Error occurred.", "Error");

            }
        }

        private void CancelBtn_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void UploadBtn_Click(object sender, EventArgs e)
        {
            if (PortfolioFile.Text == "")
            {
                MessageBox.Show("Select a file.", "Message");
                return;
            }
            try
            {
                UpdateCategory("GEN");
                UpdateBroker(BROKER_CODE);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
                return;
            }


            if (portfolio.Checked)
            {
                LogService.Add(102, Program.currentUser.UserName, "Initial portfolio loading");

                ReadportfolioHdrFile(CDSIniPortHdrFile, 3);
                ReadPortfolioFile();
                MessageBox.Show("Done");
            }
            else
            {
                LogService.Add(101, Program.currentUser.UserName, "Initial clients loading"); 
            
                ReadportfolioHdrFile(CDSClientHdrFile, 3);
                ReadCDSClientDataFile();
                MessageBox.Show("Done");
               
            }

            
           
            
        }
        
        int LineWidth = 0;
        static Dictionary<String, int> mapOffset = new Dictionary<String, int>();
        static Dictionary<String, int> mapSize = new Dictionary<String, int>();
        List<String> SymbolList = new List<String>();


        public void ReadCDSClientDataFile()
        {
            int count = 0;
            int AddedCount = 0;
            try
            {

                string[] lines = System.IO.File.ReadAllLines(PortfolioFile.Text);


                foreach (string line in lines)
                {                   
                    count++;

                    //Checking the length of a line
                    if (line.Length != LineWidth)
                    {   //commented because of empty line in data file
                        //MessageBox.Show("Error in Line " + count + " of the  data file.\n" +
                        //               "Please check the file and try again.");
                        //return;
                        continue;
                    }
                   
                    String JointACNo = GetValue("joint_ac_no", line);
                    if (JointACNo.Length == 1)
                        JointACNo = "0" + JointACNo;

                    String ClientCode = BROKER_CODE + "-" +
                                        GetValue("client_prefix", line) + "-" +
                                        GetValue("client_suffix", line) + "-" +
                                        JointACNo;

                    Client NewClient = new Client();
                    try
                    {

                        NewClient.Code = ClientCode;
                        NewClient.Title = GetValue("title", line);
                        NewClient.Initials = GetValue("initials", line);
                        NewClient.Surname = GetValue("surname", line);
                        NewClient.OtherNames = GetValue("other_names", line);
                        NewClient.Broker = BROKER_CODE;
                        NewClient.Address_1 = GetValue("address1", line);
                        NewClient.Address_2 = GetValue("address2", line);
                        NewClient.Address_3 = GetValue("address3", line);
                        //NewClient.Address_4 = GetValue("country", line);
                        NewClient.RegDate = DateTime.Now.Date;
                        NewClient.Advisor = "GEN";
                        NewClient.Category = "GEN";

                        ClientService.Add(NewClient);
               
                        
                    }
                    catch (System.Data.OracleClient.OracleException Ora)
                    {
                        if (Ora.Code == 1)
                        {
                           ClientService.Update(NewClient);
                        }
                        else
                            MessageBox.Show(Ora.Message, "Error!");

                    }
                    
                }
                
            }
            catch (Exception fileEx)
            {
                MessageBox.Show(fileEx.Message);
            }

        }


        public void ReadportfolioHdrFile(String FilePath, int StartRow)
        {
            try
            {
                mapOffset.Clear();
                mapSize.Clear();
                string[] lines = System.IO.File.ReadAllLines(FilePath);
                int count = 0;
                int Offset = 0;
               
                foreach (string line in lines)
                {
                    count++;
                    if (count < StartRow)
                        continue;

                    String ClmName = line.Substring(0, 20).Trim();
                    String size = line.Substring(32, 2);
                    int iSize = 0;
                    try
                    {
                        iSize = Int16.Parse(size);

                    }
                    catch (Exception ee)
                    {
                        continue;
                    }
                    mapSize.Add(ClmName, iSize);
                    mapOffset.Add(ClmName, Offset);

                    Console.WriteLine(ClmName + " " + iSize + " " + Offset);
                    Offset = iSize + Offset;


                }
                LineWidth = Offset;

                
            }
            catch (Exception fileEx)
            {
                MessageBox.Show(fileEx.Message);
            }

        }

        


        private void ReadPortfolioFile()
        {
            try
            {

                List<String> ClientsList = ClientService.GetClientCodeCollection();
                SymbolList.Clear();
                SymbolList = SecurityServices.GetSecSymbolList();

                string[] lines = System.IO.File.ReadAllLines(PortfolioFile.Text);
                int count = 0;


             
                if (lines.Length <= 0)
                {
                    MessageBox.Show("No data available", "Message");
                    return;
                }

                PortfolioServices.Truncate();

                foreach (string line in lines)
                {
                   
                    
                    //Checking the length of a line
                    if (line.Length != LineWidth)
                    {
                       //commented because of empty line in data file
                       // MessageBox.Show("Error in Line " + count + " of the portfolio data file.\n" +
                       //                "Please check the file and try again.");
                       // return;
                        continue;
                    }
                    count++;

                    int Quan = Int32.Parse(GetValue("balance", line));

                    String JointACNo = GetValue("joint_ac_no", line);
                    if (JointACNo.Length == 1)
                        JointACNo = "0" + JointACNo;

                    String ClientCode = BROKER_CODE + "-" +
                                        GetValue("client_prefix", line) + "-" +
                                        GetValue("client_suffix", line) + "-" +
                                        JointACNo;
                    String CompanySymbol = GetValue("company_id", line) + "-" +
                                                                GetValue("main_type", line) + "-" +
                                                                GetValue("sub_type", line);

                    //if symbol was not there in DB, it will be added.
                    UpdateSecurity(CompanySymbol);

                    if (!ClientsList.Contains(ClientCode))
                    {                       
                        QuickAddClient(ClientCode, BROKER_CODE); 
                        ClientsList.Add(ClientCode);
                        //continue;
                    }


                    try
                    {
                        Updateportfolio(ClientCode, CompanySymbol, Quan);                     
                    }
                    catch (System.Data.OracleClient.OracleException Ora)
                    {
                     
                        MessageBox.Show(Ora.Message, "Error!");

                    }         

                }


            }
            catch (Exception fileEx)
            {
                //throw;
                MessageBox.Show(fileEx.Message, "Error");
            }
        }


        private void Updateportfolio(String ClientCode, String CompanySymbol, int Quantity)
        {
            Portfolio ClPort = PortfolioServices.GetPortfolioByCodeAndSymbol(ClientCode, CompanySymbol);

            if (ClPort == null)
            {
                ClPort = new Portfolio();
                ClPort.Code = ClientCode;
                ClPort.Symbol = CompanySymbol;
                ClPort.Quantity = Quantity;

                PortfolioServices.Add(ClPort);
            }
            else
            {
                ClPort.Quantity = Quantity;
                if (ClPort.Quantity == 0)
                {
                    PortfolioServices.Delete(ClientCode, CompanySymbol);
                }
                else
                {
                    PortfolioServices.Update(ClPort);
                }

            }

        }

        static String GetValue(String ClmName, String Line)
        {
            String value = "";
            value = Line.Substring(mapOffset[ClmName], mapSize[ClmName]);
            return value.Trim();
        }


        private void UpdateSecurity(String CompanySymbol)
        {
            //Security SecObj = SecurityServices.GetSecurityBySymbol(CompanySymbol);

            if (!SymbolList.Contains(CompanySymbol))
            {
                try
                {
                    Security SecObj = new Security();
                    SecObj.Name = "";
                    SecObj.Symbol = CompanySymbol;
                    SecObj.MarketValue = 0;
                    SecObj.MarginPercentage = 100;
                    SecurityServices.Add(SecObj);

                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Database Error", "Error");
                    return;
                }

                SymbolList.Add(CompanySymbol);
            }

        }


        private void QuickAddClient(String ClientCode, String BrockerCode)
        {
            try
            {
                Client NewClient = new Client();

                NewClient.Code = ClientCode;
                NewClient.Broker = BrockerCode;
                NewClient.RegDate = DateTime.Now.Date;
                NewClient.Advisor = "GEN";
                NewClient.Category = "GEN";

                ClientService.Add(NewClient);
                //CDSTranServices.Add(trans);

            }
            catch (System.Data.OracleClient.OracleException Ora)
            {
                if (Ora.Code == 1)
                {
                    //LogBox.AppendText("Client already exist.( Client Code -" + ClientCode + " )\n");
                }
                else
                    MessageBox.Show(Ora.Message, "Error!");

            }

        }

        private void browse_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            //openFileDialog1.InitialDirectory = "D:\\";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    PortfolioFile.Text = openFileDialog1.FileName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }


        private void UpdateCategory(String Category)
        {
            ClientCategory NwCategory = ClientCategoryServices.GetClientCategoryByCode(Category);

            if (NwCategory == null)
            {
                NwCategory = new ClientCategory();
                NwCategory.Code = "GEN";
                NwCategory.Description = "General";

                ClientCategoryServices.Add(NwCategory);
            }

        }

        private void UpdateBroker(String BrokerCode)
        {
            Broker NwBroker = BrokerServices.GetBrokerByCode(BrokerCode);

            if (NwBroker == null)
            {
                NwBroker = new Broker();
                NwBroker.Code = BrokerCode;
                NwBroker.Name = BrokerCode;
                NwBroker.CreatedDate = DateTime.Now.Date;


                BrokerServices.Add(NwBroker);
            }

        }


    }
}
